package com.tsingtree.modular.controller.view;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tsingtree.base.auth.annotion.Permission;
import com.tsingtree.base.auth.context.LoginContextHolder;
import com.tsingtree.base.auth.model.LoginUser;
import com.tsingtree.base.pojo.page.LayuiPageInfo;
import com.tsingtree.modular.entity.NanUser;
import com.tsingtree.modular.entity.NanUserDevice;
import com.tsingtree.modular.enums.CommonStatusEnum;
import com.tsingtree.modular.model.params.NanUserParam;
import com.tsingtree.modular.service.NanUserDeviceService;
import com.tsingtree.modular.service.NanUserService;
import com.tsingtree.modular.util.Utils;
import com.tsingtree.roses.core.base.controller.BaseController;
import com.tsingtree.roses.core.reqres.response.ResponseData;
import com.tsingtree.sys.core.constant.Const;
import com.tsingtree.sys.modular.system.service.IRedisUtilService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.util.*;


/**
 * 用户控制器
 *
 * @author jagger
 */
@Controller
@Slf4j
@RequestMapping("/nanUser")
public class NanUserController extends BaseController {

    private String PREFIX = "/nanUser";

    @Autowired
    private NanUserService nanUserService;

    @Autowired
    private IRedisUtilService redisUtilService;

    @Autowired
    private NanUserDeviceService nanUserDeviceService;

    /**
     * 跳转到主页面
     *
     * @author jagger
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/nanUser.html";
    }

    /**
     * 新增页面
     *
     * @author jagger
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/nanUser_add.html";
    }

    /**
     * 编辑页面
     *
     * @author jagger
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/nanUser_edit.html";
    }

    /**
     * 新增接口
     *
     * @author jagger
     */
    @RequestMapping("/addItem")
    @Permission
    @ResponseBody
    public ResponseData addItem(NanUserParam nanUserParam) {
        this.nanUserService.add(nanUserParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author jagger
     */
    @RequestMapping("/editItem")
    @Permission
    @ResponseBody
    public ResponseData editItem(NanUserParam nanUserParam) {
        NanUser nanUser = nanUserService.getById(nanUserParam.getId());
        nanUser.setStatus(nanUserParam.getStatus());
        String oldPhone = nanUser.getEmail();
        nanUser.setEmail(nanUserParam.getEmail());
        nanUser.setIsOfficial(nanUserParam.getIsOfficial());
        nanUser.setIsVip(nanUserParam.getIsVip());
        nanUser.setTag(nanUserParam.getTag());
        try {
            nanUserService.updateUser(nanUser);
        } catch (Exception e) {
            log.error("error update user: {}", nanUser.getId(), e);
            return ResponseData.error("修改失败，请稍后操作");
        }
        if (nanUserParam.getStatus() == CommonStatusEnum.FORBIDDEN.getKey()) {
            redisUtilService.set("user_frozen:" + nanUserParam.getId(), "1");
        } else {
            redisUtilService.delete("user_frozen:" + nanUserParam.getId());
        }
        if (!oldPhone.equals(nanUser.getEmail())) {
            redisUtilService.delete("user_token:" + nanUser.getId());
        }
        return ResponseData.success();
    }

    /**
     * 重置密码
     *
     * @author jagger
     */
    @RequestMapping("/delete")
    @Permission
    @ResponseBody
    public ResponseData delete(NanUserParam nanUserParam) {
        NanUser nanUser = nanUserService.getById(nanUserParam.getId());
        nanUser.setPwd(Utils.MD5("123456"));
        if(!this.nanUserService.updateById(nanUser)){
            return ResponseData.error("操作失败，请稍后再试");
        }
        return ResponseData.success();
    }

    /**
     * 查询列表
     *
     * @author jagger
     */
    @ResponseBody
    @Permission(link = "/list")
    @RequestMapping("/export")
    public void export(NanUserParam nanUserParam, HttpServletResponse response) throws IOException {
        String email = nanUserParam.getEmail();
        Integer id = nanUserParam.getId();
        Integer sex = nanUserParam.getSex();
        String nickName = nanUserParam.getNickName();
        Integer status = nanUserParam.getStatus();
        String tag = nanUserParam.getTag();
        String beginTime = nanUserParam.getBeginTime();
        String endTime = nanUserParam.getEndTime();
        QueryWrapper<NanUser> queryWrapper = new QueryWrapper<>();
        if(StringUtils.hasText(email)){
            queryWrapper.eq("email", email);
        }
        if(Objects.nonNull(id)){
            queryWrapper.eq("id", id);
        }
        if(StringUtils.hasText(nickName)){
            queryWrapper.eq("nick_name", nickName);
        }
        if(Objects.nonNull(sex)){
            queryWrapper.eq("sex", sex);
        }
        if(Objects.nonNull(status)){
            queryWrapper.eq("status", status);
        }
        if(StringUtils.hasText(tag)){
            String[] tagList = tag.split(",");
            queryWrapper.and((q) -> {
                for (String t : tagList) {
                    q.or().like("tag", t);
                }
                return q;
            });
        }
        if(StringUtils.hasText(beginTime)){
            queryWrapper.gt("create_time", beginTime);
        }
        if(StringUtils.hasText(endTime)){
            queryWrapper.le("DATE_FORMAT(create_time, '%Y-%m-%d')", endTime);
        }
        List<NanUser> userList = this.nanUserService.list(queryWrapper);
        for (NanUser nanUser : userList) {
            if(StringUtils.hasText(nanUser.getAvatar())){
                nanUser.setUrl(new URL(Const.OSS_CDN + nanUser.getAvatar()));
            }
        }
        List<NanUserDevice> list = nanUserDeviceService.list(new QueryWrapper<NanUserDevice>().orderByAsc("id"));
        Map<Integer, NanUserDevice> map = new HashMap<>();
        list.forEach(device -> {
            if(!map.containsKey(device.getUserId())){
                map.put(device.getUserId(), device);
            }
        });
        userList.forEach(user -> {
            NanUserDevice device = map.get(user.getId());
            if(Objects.nonNull(device)){
                user.setSellerId(device.getSellerId()).setDeviceCode(device.getCode());
            }
        });
        String title = "会员数据";
        String filter = nanUserParam.getFilter();
        String[] filterRes = filter.split(",");
        List<String> strings = Arrays.asList(filterRes);
        Set<String> includeColumnFiledNames = new HashSet<>(strings);
        Utils.setExcelResponseProp(response, title);
        EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .includeColumnFieldNames(includeColumnFiledNames)
                .head(NanUser.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(title)
                .doWrite(userList);
    }

    /**
     * 备注
     *
     * @author jagger
     */
    @RequestMapping("/setUserTag")
    @Permission(link = "/addItem")
    @ResponseBody
    public ResponseData setUserTag(String ids, String tag, String r) {
        if(!StringUtils.hasText(ids)){
            return ResponseData.error("请至少选择一名用户");
        }
        String[] uids = ids.split(",");
        List<NanUser> list = new ArrayList<>();
        if(StringUtils.hasText(r)){
            //删除
            for(String uid: uids){
                Integer userId = Integer.parseInt(uid);
                NanUser nanUser = nanUserService.getById(userId);
                String oldTag = nanUser.getTag();
                String[] newTag = tag.split(",");
                if(StringUtils.hasText(oldTag)){
                    List<String> hadTag = new ArrayList<>(Arrays.asList(oldTag.split(",")));
                    for (String s : newTag) {
                        hadTag.remove(s);
                    }
                    nanUser.setTag(String.join(",", hadTag));
                    list.add(nanUser);
                }
            }
        }else{
            for(String uid: uids){
                Integer userId = Integer.parseInt(uid);
                NanUser nanUser = nanUserService.getById(userId);
                String oldTag = nanUser.getTag();
                String[] newTag = tag.split(",");
                if(StringUtils.hasText(oldTag)){
                    List<String> hadTag = new ArrayList<>(Arrays.asList(oldTag.split(",")));
                    for (String s : newTag) {
                        if(!hadTag.contains(s)){
                            hadTag.add(s);
                        }
                    }
                    nanUser.setTag(String.join(",", hadTag));
                    list.add(nanUser);
                }else{
                    nanUser.setTag(tag);
                    list.add(nanUser);
                }
            }
        }

        if(!CollectionUtils.isEmpty(list)){
            nanUserService.updateBatchById(list);
        }
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author jagger
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(NanUserParam nanUserParam) {
        NanUser detail = this.nanUserService.getById(nanUserParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author jagger
     */
    @ResponseBody
    @Permission
    @RequestMapping("/list")
    public LayuiPageInfo list(NanUserParam nanUserParam) {
        String tagStr = nanUserParam.getTag();
        if(StringUtils.hasText(tagStr)){
            List<String> tagList = Arrays.asList(tagStr.split(","));
            nanUserParam.setTagList(tagList);
        }
        return this.nanUserService.findPageBySpec(nanUserParam);
    }

    /**
     * 获取官方用户列表
     *
     * @author claude
     */
    @ResponseBody
    @RequestMapping("/officialList")
    public ResponseData officialList() {
        QueryWrapper<NanUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_official", true);
        queryWrapper.select("id", "nick_name", "avatar");
        List<NanUser> officialUsers = this.nanUserService.list(queryWrapper);
        return ResponseData.success(officialUsers);
    }

}


